package xin.nick.system.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xin.nick.common.core.util.MyAssert;
import xin.nick.system.config.ApplicationSystemProperties;
import xin.nick.system.domain.vo.FileUploadVO;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author Nick
 * @since 2023/1/4/004
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class LocalFileService {

    private final ApplicationSystemProperties systemProperties;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public FileUploadVO uploadFile(MultipartFile file) {
        // 获取到文件
        // 将文件保存到指定目录
        // 返回文件名

        // 原始文件名,取出文件后缀
        String originalFilename = file.getOriginalFilename();
        String[] arr = originalFilename.split("\\.");
        String suffix = arr[arr.length - 1];

        // 需要保存的文件名, 带上日期
        String fileName = IdUtil.fastSimpleUUID() + "." + suffix;

        // 目录带上日期
        LocalDateTime now = LocalDateTime.now();
        String dateFolder = now.getYear() + "/" + now.getMonthValue() + "/" + now.getDayOfMonth();

        String localFileSavePath = systemProperties.getLocalFileSavePath();
        // 没有目录则创建
        File folderFile = new File(localFileSavePath + dateFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        // 写到文件
        String finalFileName = localFileSavePath + dateFolder + "/" + fileName;
        File finalFile = new File(finalFileName);

        // 写出文件
        try {
            FileUtil.writeBytes(file.getBytes(), finalFile);
        } catch (IOException e) {
            log.error("普通文件上传出错:", e);
            MyAssert.throwException("普通文件上传出错,请联系管理员");
        }

        String fileUri = new StringBuilder(systemProperties.getFileRequestPath())
                .append("/")
                .append(dateFolder)
                .append("/")
                .append(fileName)
                .toString();
        String fileUrl = new StringBuilder(systemProperties.getProjectUrl())
                .append(fileUri)
                .toString();

        // 返回对象
        FileUploadVO fileUploadVO = new FileUploadVO();
        fileUploadVO.setFileUrl(fileUrl);
        fileUploadVO.setFileUri(fileUri);
        return fileUploadVO;
    }
}
